package com.jch.integration.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component("nettyServer")
public class NettyServer {

    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final EventLoopGroup boss = new NioEventLoopGroup(1);
    private final EventLoopGroup worker = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture bind(InetSocketAddress address) {
        ChannelFuture cf = null;

        ServerBootstrap b = new ServerBootstrap()
                .group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childHandler(new ServerChannelInitializer());

        try {
            cf = b.bind(address).sync(); // 等待连接
            channel = cf.channel();
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }finally {
            if (null != cf && cf.isSuccess()){
                logger.info("Netty Server Start !");
            }else {
                logger.info("Netty Server Start Error！");
            }
        }
        return cf;
    }

    public void destroy(){
        if (null == channel) return;
        channel.close();
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }

    public Channel getChannel(){
        return channel;
    }
}
